package tacos.web.api;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.rest.webmvc.RepositoryRestController;
import org.springframework.hateoas.CollectionModel;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import tacos.domain.Taco;
import tacos.repository.TacoRepository;
import tacos.web.resources.TacoResource;
import tacos.web.resources.TacoResourceAssembler;

import java.util.List;

import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn;

@RepositoryRestController // P161 表示使用与 datarest 相同的基础路径 base-url
/**
 *  需要注意的是，尽管@RepositoryRestController与@RestController非常相似，但是他们并不存在相同的语义。
 *  具体来讲，它并不能保证处理器方法返回的值自动写入响应体中。
 *  所有我们要么为方法添加@RequestBoday注解，要么包装响应数据的ResponseEntity。
 */
//@RequestMapping(name = "/tacos", produces="application/json")
public class RecentTacosController {
    private TacoRepository tacoRepository;

    public RecentTacosController(TacoRepository tacoRepository) {
        this.tacoRepository = tacoRepository;
    }

    @GetMapping(path = "/tacos/recent",produces = "application/hal+json")
    public ResponseEntity<CollectionModel<TacoResource>> recentTacos(){
        PageRequest page = PageRequest.of(0,12, Sort.by("createdAt").descending());
        List<Taco> tacos = tacoRepository.findAll(page).getContent();

            CollectionModel<TacoResource> tacoResources = new TacoResourceAssembler(RecentTacosController.class, TacoResource.class).toCollectionModel(tacos);
        tacoResources.add(linkTo(methodOn(RecentTacosController.class).recentTacos()).withRel("recents"));
        return new ResponseEntity<>(tacoResources, HttpStatus.OK);
    }
}
